const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const BadRequest = require('http-errors').BadRequest;
const NotFoundError = require('../../utils/errors').NotFoundError;
const { success, failure } = require('../../utils/responses');
// 连接 MongoDB 数据库，替换为你自己的真实连接字符串
mongoose.connect('mongodb://localhost:27017/control-book', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const Category = require('../../models/category'); // 假设你有对应的 Mongoose 模型定义文件
const Book = require('../../models/book');


// 获取所有分类
router.get('/', async function (req, res) {
  try {
      const query = req.query;

      // 获取分页所需要的两个参数，currentPage和pageSize
      // 如果没有传递这两个参数，就使用默认值
      // 默认是1页，默认每页显示10条数据
      const currentPage = Math.abs(Number(query.currentPage) || 1);
      const pageSize = Math.abs(Number(query.pageSize) || 10);

      const skip = (currentPage - 1) * pageSize;

      const condition = {};

      if (query.rank) {
          condition.rank = query.rank;
      }
      if (query.borrowName) {
          condition.borrowName = query.borrowName;
      }

      const totalCount = await Category.countDocuments(condition);

      const categories = await Category.find(condition)
        //  .populate('_id')
         .skip(skip)
         .limit(pageSize)
         .sort({ _id: -1 });

         
      success(res, '分类查询成功', {
          categories,
          pagination: {
              total: totalCount,
              currentPage,
              pageSize
          }
      });
  } catch (error) {
      failure(res, error);
  }
});

// 获取单个分类详细信息
router.get('/:_id', async function (req, res) {
  try {
      const category = await Category.findById(req.params._id).populate('books');
      if (!category) {
          throw new NotFoundError(`ID: ${req.params._id}的分类未找到`);
      }
      success(res, '分类查询成功', { category });
  } catch (error) {
      failure(res, error);
  }
});

// 创建分类
router.post('/', async function(req, res) {
  try {
    const category = new Category(req.body);
    console.log(category)
      await category.save();
      success(res, '分类创建成功', { category });
  } catch (error) {
      console.log(req.body)
      console.log(error)
      failure(res, error);
  }
})

function filterBook(req) {
  return {
    name: req.body.name,
    rank: req.body.rank,
    createdAt: now.toLocaleDateString(),
    updatedAt: now.toLocaleDateString(),
  }
}

module.exports = router;